// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const userCollection = db.collection('user')
const likeCollection = db.collection('liker_liked')
const _ = db.command


// 云函数入口函数
exports.main = async (event, context) => {
  let voiceList = []
  let outputList = []
  const wxContext = cloud.getWXContext()

  await likeCollection.where({
    likerOpenId: _.neq(wxContext.OPENID),
    likedOpenId: wxContext.OPENID
  }).skip(0).limit(20).field({
      likerOpenId: true
    }).get().then(res => {
      voiceList = res.data.map(item => {
        return item.likerOpenId
      })
    })
  voiceList = Array.from(new Set(voiceList))

  for (let item of voiceList) {
    let obj = {}
    await userCollection.where({
      _openid: item
    }).get().then(res => {
      obj = {
        userStar: res.data[0]
      }
    })

    await likeCollection.where({
      likerOpenId: item,
      likedOpenId: wxContext.OPENID
    }).count().then(count => {
      obj.perStarCount = count.total
    })
    outputList.push(obj)
  }

  return outputList
}